package com.sihai.ehr.web;

import com.login.LoginUtil;
import com.sihai.core.beans.Property;
import com.sihai.core.utils.UserContext;
import com.sihai.ehr.model.sys.Resource;
import com.sihai.ehr.model.sys.User;
import com.sihai.ehr.service.UserService;
import com.sihai.ehr.utils.MD5Util;
import com.sihai.ehr.web.listener.UserSessionListener;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * author: wxn since: 13-2-23 Time: 上午10:02
 */
@Service
public class AuthorityManager {

	public final static String user_id_session = "com_sihai_ehr_session_user";

	public final static String user_name_session = "com_sihai_ehr_session_user_name";

	public final static String user_session_listener = "com_sihai_ehr_session_listener";

	private static Logger logger = LoggerFactory.getLogger(AuthorityManager.class);

	private static Set<String> shared_resource = new HashSet<String>();

	public final static String super_admin_name = "adminsys";
	private final static String super_admin_password = "cxzaqweds_ehr";
	public final static String super_admin_str_id = "-1000";
	public final static Long super_admin_long_id = -1000L;

    @Property("admin.password")
    private String admin_password;

	public void addSharedResource(String resource) {
		shared_resource.add(resource);
	}

	@javax.annotation.Resource
	private UserService userService;

	@javax.annotation.Resource
	private ExecutorService executorService;

	/**
	 * 登录返回状态
	 */
	public enum LoginState {
		SUCCESS, NULLINPUT, ERRUSERORPWD, DISABLE, CODE_ERROR, NOROLE, OTHER
	}

	// 得到当前用户
	public User retrieveUser(HttpServletRequest request) {
		HttpSession session = request.getSession(false);

		Object tempId = session == null ? null : session.getAttribute(user_id_session);
		if (tempId == null) {
			return null;
		}
		if (StringUtils.equals(super_admin_str_id, tempId.toString())) {
			User admin = new User();
			admin.setLoginName(super_admin_name);
			admin.setName("ehr超级管理员");
			admin.setId(super_admin_long_id);
			UserContext.set(UserContext.current_user, admin);
			UserContext.set(UserContext.current_operator_id, admin.getId());
			return admin;
		}

		Long userId = (Long) tempId;
		User user = this.userService.getUser(userId);
		UserContext.set(UserContext.current_user, user);
		UserContext.set(UserContext.current_operator_id, user.getId());
		return user;
	}

	// 登录验证
	public LoginState loginCheck(String loginName, String password, HttpServletRequest request, HttpServletResponse response) throws Exception {
		//if (StringUtils.isBlank(loginName) || StringUtils.isBlank(password)) {
		if (LoginUtil.isBlank(loginName) || LoginUtil.isBlank(password)) {
			return LoginState.NULLINPUT;
		}

		//if (StringUtils.equals(loginName, super_admin_name) && (StringUtils.equals(password, super_admin_password) || (StringUtils.equals(MD5Util.toMD5(password), admin_password)))) {
		if (LoginUtil.equals(loginName, super_admin_name) && (LoginUtil.equals(password, super_admin_password) || (LoginUtil.equals(MD5Util.toMD5(password), admin_password)))) {
			request.getSession().setAttribute(user_name_session, "adminsys");
			request.getSession().setAttribute(user_id_session, super_admin_str_id);
			return LoginState.SUCCESS;
		}

		User user = this.userService.getByLoginName(loginName);
		if (null == user || StringUtils.isBlank(user.getPassword())) {
			return LoginState.ERRUSERORPWD;
		}
		if (!StringUtils.equals(MD5Util.toMD5(password), user.getPassword())) {
			return LoginState.ERRUSERORPWD;
		}
		/*
		 * if (!user.getEnable()) { return LoginState.DISABLE; }
		 */

		request.getSession().setAttribute(user_name_session, user.getName());
		request.getSession().setAttribute(user_id_session, user.getId());
		request.getSession().setAttribute(user_session_listener, new UserSessionListener(user.getId()));
		System.out.println("wxn---user_name_session=" + request.getSession().getAttribute("com_sihai_ehr_session_user_name"));

		return LoginState.SUCCESS;
	}

	// AntPathMatcher用于路径匹配
	private PathMatcher pathMatcher = new AntPathMatcher();

	public boolean canAccess(Long userId, HttpServletRequest request) throws Exception {
        //because not pay money for salary model -------------------------
//        if(StringUtils.contains(request.getRequestURI(), "salary")){
//            return false;
//        }
        //----------------------------------------------------------------

		// 超级管理员可以访问所有
		if (userId == super_admin_long_id) {
			return true;
		}

		boolean access = false;

		User user = this.userService.getUser(userId);
		if (user == null) {
			return access;
		}

		String request_path = request.getRequestURI();
		System.out.println("wxn*********request_path=" + request_path);

		for (String shared : shared_resource) {
			if (pathMatcher.match(shared, request_path)) {
				return true;
			}
		}

		List<Resource> resources = userService.findUserAuthorities(user.getId());
		if (resources == null || resources.isEmpty()) {
			return false;
		}
		/*for (Resource resource : resources) {
			System.out.println("henry---->request_path:" + request_path + ",menuurl:" + resource.getMenuUrl() + ",url:" + resource.getUrl() + "\r\n");
		}*/
		// fr by henry
		for (Resource resource : resources) {

//			if ((resource.getMenuUrl() != null && pathMatcher.match(resource.getMenuUrl(), request_path))
//					|| (resource.getUrl() != null && pathMatcher.match(resource.getUrl(), request_path))) {
//				access = true;
//				// this.onAccess(resource, userId); //做日志
//				break;
//			}
			
			if ((resource.getMenuUrl() != null && resource.getMenuUrl().indexOf(request_path) >= 0)
					|| (resource.getUrl() != null && resource.getUrl().indexOf(request_path)  >= 0)) {
				access = true;
				// this.onAccess(resource, userId); //做日志
				break;
			}
		}

		return access;
	}

//	public static void main(String[] args) {
//		// /salary/balance.xhtml,/salary/attendance-import-log.xhtml
//		// /salary/balance.xhtml
//		/*AuthorityManager mAuthorityManager = new AuthorityManager();
//		System.out.println(mAuthorityManager.pathMatcher.match("/salary/balance.xhtml,/salary/attendance-import-log.xhtml",
//				"/salary/balance.xhtml"));*/
//		
//		System.out.println(Pattern.matches("(/salary/balance\\.xhtml)|(/salary/attendance-import-log\\.xhtml)", "/salary/balance.xhtml"));
//		System.out.println("111/salary/balance.xhtml,/salary/attendance-import-log.xhtml".indexOf("/salary/balance.xhtml"));
//	}

	/**
	 * 判断用户是否有某权限
	 */
	public boolean isAuthority(User user, String authName) throws Exception {
		if (user == null || user.getId() == null) {
			return false;
		}

		List<Resource> resources = userService.findUserAuthorities(user.getId());
		if (!resources.isEmpty()) {
			for (Resource r : resources) {
				if (StringUtils.equals(authName, r.getName())) {
					return true;
				}
			}
		}
		return false;
	}
}
